import store from "../redux/store"
import '../assets/css/Chat.css'
import { useLocation, useNavigate } from "react-router-dom"
import { createRef, useEffect } from "react"
import { initWebSocket, onClose, sendMsg } from "../utils/ws"
import { saveBox } from "../redux/action"

function Chatting() {
  const navigate = useNavigate()
  const location = useLocation()
  const inputRef = createRef()
  const sendRef = createRef()
  const emoRef = createRef()
  const boxRef = createRef()
  let emojiArr = ['😀', '😁', '😂', '😃', '😄', '😅', '😆', '😉', '😊', '😋',
    '😎', '😍', '😘', '😗', '😙', '😚', '🌍', '😇', '😐', '😑', '😶', '😏', '😣', '😥',
    '😮', '😯', '😪', '😫', '😴', '😌', '😛', '😜', '😝', '😒', '😓', '😔', '😕', '😲',
    '😷', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😬', '😰', '😱', '😳',
    '😵', '😡', '😠']
  initWebSocket(`ws://localhost:8080/chatting/${location.state.name}`, store.getState().TokenMode.token)
  useEffect(() => {
    store.dispatch(saveBox(boxRef.current))
  }, [])
  return (
    <div>
      <div className="chattingHead">
        <span className="chattingBack" onClick={() => {
          onClose();
          navigate('/main/Center')
        }}>{"<"}</span>
        <div className="word">{location.state.name}</div>
      </div>
      <div className="chattingBox" ref={boxRef}>
      </div>
      <div className="chattingSend" ref={sendRef}>
        <input type="" className="chattingMessage" placeholder="请输入" ref={inputRef} />
        <div className="chattingBtn" onClick={() => {
          chatMsg(inputRef.current.value, boxRef.current)
          inputRef.current.value = ''
        }}>发送</div>
        <div className="emo" onClick={() => { showEmo(sendRef.current, emoRef.current, boxRef.current) }}>
          <img src={require('../assets/images/smile.png')} width="100%" alt="" />
        </div>
      </div>
      <div className="emoBox" ref={emoRef}>
        {
          emojiArr.map((item, index) => (
            <span className="emoji" onClick={(e) => { sendEmo(e, inputRef.current) }}>{item}</span>
          ))
        }
      </div>
    </div>
  )
}

async function showEmo(sendDom, emoDom, box) {
  sendDom.style.bottom = sendDom.style.bottom == '200px' ? '0' : '200px'
  emoDom.style.display = emoDom.style.display == 'block' ? 'none' : 'block'
}

function sendEmo(e, input) {
  input.value += e.target.innerHTML
}

async function chatMsg(msg, box) {
  if(msg.length == 0) {
    return 
  }
  if(msg.length > 25) {
    alert('最多输入25个字')
    return
  }
  sendMsg(msg)
  if (box.scrollHeight > 620) {
    await new Promise(() => {
      setTimeout(() => {
        box.scrollTop = 99999
      }, 0)
    })
  }
}

export default Chatting